<template>
    <div>
        <el-dialog :visible.sync="backstageSendCouponDialog" title="发放优惠券" :close-on-click-modal="false" >

            <el-form :model="dataForm" size="mini" ref="dataForm"  :rules="dataFormRules">
                <el-form-item >
                    <span class="color333 font16 ml10">优惠券名称：</span>
                    <span class="color333 font16">{{couponInfo.promName}}</span>
                </el-form-item>
                <el-form-item label="" class="w178 mt30">
                    <span class="color333 font16 ml10">可发行数量：</span>
                    <span class="color333 font16"> {{couponInfo.issuableTotal}}</span>
                </el-form-item>
                <el-form-item  class="mt30">
                    <span class="color333 font16 ml26" >发送方式：</span>
                   <span class="color333 font16">短信</span> 
                </el-form-item>
                <el-form-item label="输入手机号：" prop="phoneList" class=" mt30 mb60">
                    <el-input
                        type="textarea"
                        autosize
                        :rows="6"
                        placeholder="输入用户手机号，多个时用英文的逗号隔开"
                        v-model="dataForm.phoneList"
                        class="w632 mb30">
                    </el-input>
                    <div class="importPhone">
                        <a class="download" href="/static/excels/sendCoupon-import-phone.xlsx" download="导入手机号模板.xls">下载模板</a>
                        <!-- <el-button class="importPhone-item" size="small" type="primary" @click="downlodTemplate">下载模板</el-button> -->
                        <el-upload
                            class="upload-demo importPhone-item"
                            action=""
                            :on-change="handleChange"
                            :on-remove="handleRemove"
                            :on-exceed="handleExceed"
                            :show-file-list="false"
                            accept="application/vnd.openxmlformats-    
                            officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                            :auto-upload="false">
                            <el-button size="small" class="searchButton">点击上传</el-button>
                        </el-upload>
                    </div>
                </el-form-item>
            </el-form>
            <div>
                <el-button @click="chanel" class="cancelButton mr60">取消</el-button>
                <el-button class="searchButton" @click="next">下一步</el-button>
            </div>

            <el-dialog
                width="60%"
                title="发送短信"
                :visible.sync="sendSmsDialog"
                :close-on-click-modal="false"
                append-to-body>

                <el-form :model="smsForm" size="mini" ref="smsForm" :rules="rules">
                    <el-form-item label="短信模板："  class="mb30" :required="true" :show-message="false">
                        <el-select v-model="template" placeholder="选择短信模板" filterable size="mini"  @change="templateSelect" class="w495 mr20 turnBlock f_l">
                            <el-option v-for="item in templateList" :key="item.thirdTemplateId" :label="item.templateName" :value="item.id"></el-option>
                        </el-select>
                        <el-button class="cancelButton mr20 turnBlock f_l" @click="refreshTemplate">刷新</el-button>
                    </el-form-item>
                    <el-form-item label="短信内容：" class=" mb30 txt" :required="true" :show-message="false">
                        <div class="w706 flex" v-html="smsContent">
                        
                        </div>
                    </el-form-item>
                    <el-form-item label="测试发送：" prop="testReceiver" class="phone labelMarginLeft5 mb60">
                        <el-input class="w495 mr20" v-model="smsForm.testReceiver" placeholder="输入测试发送手机号" maxlength="11" oninput="value=value.replace( /[^\d]/g,'')" clearable></el-input>
                        <el-button class="searchButton" @click="sendTestMessage">发送</el-button>
                    </el-form-item>
                </el-form>
                <div class="save t_c ">
                    <el-button class="cancelButton mr60" size="small" @click="sendSmsDialog = false">上一步</el-button>
                    <el-button class="searchButton" @click="saveBranchNode">确认发送</el-button>
                </div>
            </el-dialog>


        </el-dialog>

        <el-dialog :visible.sync="backstageSendCouponLog" title="发放记录" :close-on-click-modal="false" width="60%">
            <div class="log-title">
                <div>
                    优惠券名称：{{couponInfo.promName}}
                </div>
                <div>
                    <el-button class="cancelButton" :size="size" @click="queryCouponPeriod">刷新</el-button>
                </div>
            </div>
            <el-table
                :data="tableData"
                :header-cell-style="{ 'color': '#FFF','background-color': '#409EFF','text-align': 'center'}"
                :highlight-current-row="true"
                :max-height="1500"
                :size="size"
                v-loading="loading"
                :align="align"
                >
                    <el-table-column prop="id" label="ID"  align="center"></el-table-column>
                    <el-table-column label="发放成功数量" align="center">
                        <template slot-scope="scope">
                            {{scope.row.status == 1 ? '-' : scope.row.periodNum}}
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" align="center">
                        <template slot-scope="scope">
                            {{scope.row.status == 1 ? '执行中' : '已完成'}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="发放时间" align="center"></el-table-column>

            </el-table>
            <div class="t_r">
                <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageRequest.start"
                :page-sizes="[10, 15, 20]"
                :page-size="pageRequest.limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
                </el-pagination>
            </div>
        </el-dialog>

        <el-dialog
            :visible.sync="dialogVisible"
            width="30%"
            :before-close="closeDialogVisible"
            :close-on-click-modal="false"
            center>
            <div style="text-align: center;">
                <div>批量发放优惠券需要若干分钟，请在发放记录中刷新状态</div>
                <img style="margin-top: 15px;" src="/static/images/loading.gif" /> 
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button class="searchButton" @click="closeDialogVisible">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { isEmail,isMobile } from "@/utils/validate";

export default {
    name: "backstageSendCoupon",

    props:{

    },
    data(){
        var checkPhoneList = (rule, value, callback) =>{
            if(!value){
                return callback(new Error("请输入手机号"));
            }
            let myreg= /^1\d{10}$/;
            let eng = /[^\d,]]*/g;
            let flag = false;
            let phoneLengthFalg = false;
            let phone = value.split(",");
            if(phone.length < 2){
                if(phone[0].length != 11){
                    return callback(new Error("手机号格式错误，请重新输入"));
                }
                if (!myreg.test(phone[0])) {
                    return callback(new Error("手机号格式错误，请重新输入"));
                }
            }
            if(eng.test(value)){
                return callback(new Error("多个手机号时请用英文的逗号隔开"));
            }
            for (let index = 0; index < phone.length; index++) {
                if(phone[index].length != 11){
                    phoneLengthFalg = true;
                    break;
                }
                if (!myreg.test(phone[index])) {
                    flag = true;
                    break;
                }
            }
            if(phoneLengthFalg || flag){
                return callback(new Error("手机号格式错误，请重新输入"));
            }
            callback();
        }
        return{
            couponInfo: {}, //选中优惠券对象
            backstageSendCouponDialog: false,   //发送优惠券弹窗
            dataForm:{
                phoneList: ""
            },
            dataFormRules:{
                phoneList:[
                    {required: true, validator: checkPhoneList , trigger: "blur" },
                ]
            },

            sendSmsDialog: false,   //发送短信弹窗

            //表单规则
            smsForm: {
                tempId:"",
                params:{

                },
                previewContent:"",
                templateName:"",
                testReceiver:""
            },
            template: null,
            smsTmplateInfo:null,
            templateContent:"",
            smsContent: null,
            //form规则
            rules: {
            },
            templateList:[],
            params:[],

            backstageSendCouponLog: false, //发券记录
            
            tableData:[],
            total: 0,
            loading: false,
            align: "center",
            size: "mini",
            pageRequest:{
                start: 1,
                limit: 10,
                promotionId: null,

            },


            fileTemp:{},
            importPhoneList:[],

            queryPeriodStatusInterval: null,
            periodId: null,

            dialogVisible: false,

        }
    },
    methods:{
        handleCurrentChange(val){
            this.pageRequest.start = val;
            this.queryCouponPeriod();
        },
        handleSizeChange(val){
            this.pageRequest.start = 1;
            this.pageRequest.limit = val;
            this.queryCouponPeriod();
        },
        //取消
        chanel(){
            this.backstageSendCouponDialog = false;
        },
        //取消
        chanelLog(){
            this.backstageSendCouponLog = false;
        },
        //发券
        openDialog(row){
            //清空数据
            if (this.$refs['dataForm'] != undefined) {
                this.$refs['dataForm'].resetFields();
            }
            if (this.$refs['smsForm'] != undefined) {
                this.$refs['smsForm'].resetFields();
                    this.smsForm =  {
                    tempId:"",
                    params:{

                    },
                    previewContent:"",
                    templateName:"",
                    testReceiver:""
                };
                this.smsTmplateInfo = null
                this.templateContent = ""
                this.smsContent = null
                this.template = null;
            }
            //查询优惠券信息
            this.couponInfo = row;
            this.utils.request.getCouponIssuableTotal({"promotionId":row.promotionId},res=>{
                if(res.code == '0000'){
                    if(res.data != null){
                        if(Number(res.data) <= 0){
                           this.$message({message:"已达到规定发行数量，无法继续发放", type:"error"}); 
                           return false;
                        }
                       this.$set(this.couponInfo,"issuableTotal",res.data)
                    }else{
                        this.$set(this.couponInfo,"issuableTotal",'不限')
                    }
                    this.backstageSendCouponDialog = true;
                }
            })
        },
        //发券记录
        viewSendLog(row){
            //查询优惠券信息
            this.couponInfo = row;
             
            let that = this;
            let callback = function(){
                that.backstageSendCouponLog = true;
            };
            this.queryCouponPeriod(callback)
        },
        //下一步
        next(){
            this.$refs['dataForm'].validate(valid => {
                if (valid) {
                    this.sendSmsDialog = true;
                }
            })
        },
        queryCouponPeriod(callback){
            this.loading = true;
            this.pageRequest.promotionId = this.couponInfo.promotionId;
            this.utils.request.queryCouponPeriod(this.pageRequest,res=>{
                this.loading = false;
                if(res.code == '0000'){
                    this.tableData = res.data.rows;
                    this.total = Number(res.data.total);
                    if(callback != null){
                        callback();
                    }
                }
            })
        },
        /**
         * 校验手机正确性
         */
        checkTestPhone(vue){
            if(!isMobile(vue)){
                this.$message({message:"请输入正确的手机号", type:"error"});
                this.smsForm.testReceiver = "";
                return false;
            }
        },
        /**
         * 测试发送
         */
        sendTestMessage(){
            let that = this;
            if(this.smsForm.tempId =="" || this.smsForm.tempId == null){
                that.$message({message:"请选择短信模版",type:"error"})
                return false;
            }
            if(this.smsForm.testReceiver == null || this.smsForm.testReceiver == "" ){
                that.$message({ message: "请输入测试手机号", type: "error" });
                return false
            }
            if(!isMobile(this.smsForm.testReceiver)){
                this.$message({message:"请输入正确的手机号", type:"error"});
                this.smsForm.testReceiver = "";
                return false;
            }
            if(that.params.length > 0){
                for(var i=0;i<that.params.length;i++){
                var key = that.params[i];
                that.smsForm.params[key] = document.getElementById(key).value;
                if(that.smsForm.params[key]==null || that.smsForm.params[key]=='' ){
                    that.$message({ message: "请输入补全短信内容的参数", type: "error" });
                    return false;
                }
                }
            }
            that.smsForm.type = 1;
            this.utils.request.sendTestMessage(that.smsForm, res => {
                if (res.code == "0000") {
                if(res.data.code == "0"){
                    that.$message({ message: res.data.message, type: "success" });
                }else{
                    that.$message({ message: res.data.message, type: "error" });
                }
                }
            });
        },
        /**
         * 模板选择
         */
        templateSelect(val){
            let item = null;
            this.templateList.forEach(sms=>{
                if(sms.id == val){
                // this.smsInfo = sms;
                item = sms;
                }
            })
            if(item == null){
                this.$message({
                    type:"error",
                    message: "模板不存在"
                })
                return false;
            }
        
            this.smsTmplateInfo = item.templateName;
            this.smsForm.templateName = item.templateName;
            this.templateContent = item.templateContent;
            this.smsForm.tempId = item.thirdTemplateId;
            var content = item.templateContent;
            var reg="${(.*?)}";
            var textList = content.split(/\$\{[^}]+\}/);
            var paramList = content.match(/\$\{[^}]+\}/g);
            this.params = [];
            this.smsForm.params = {};
            if(paramList != null){
                for(var i=0;i<paramList.length;i++){
                this.params.push(paramList[i].replace("${","").replace("}",""));
                this.smsForm.params[paramList[i].replace("${","").replace("}","")] = "";
                content= content.replace(paramList[i],'&nbsp;&nbsp;<textarea class="textareaParm" type="text" id="'+paramList[i].replace("${","").replace("}","")+'"></textarea>&nbsp;&nbsp;');
                }
            }
            this.smsContent = content;
        },
        
        /**
         * 保存短信节点
         */
        saveBranchNode(){
            let that = this;
            if(that.smsForm.tempId =="" || that.smsForm.tempId == null){
                that.$message({message:"请选择短信模版",type:"error"})
                return false;
            }
            //判断参数是否全部输入
            if(that.params.length > 0){
                for(var i=0;i<that.params.length;i++){
                    var key = that.params[i];
                    that.smsForm.params[key] = document.getElementById(key).value;
                    if(that.smsForm.params[key]==null || that.smsForm.params[key]=='' ){
                        that.$message({ message: "请输入补全短信内容的参数", type: "error" });
                        return false;
                    }
                }
            }
            //短信预览数据组装
            var paramList = this.templateContent.match(/\$\{[^}]+\}/g);
            var content = this.templateContent;
            if(paramList != null && paramList.length > 0){
                for(var i=0;i<paramList.length;i++){
                    var key = paramList[i].replace("${","").replace("}","");
                    content= content.replace(paramList[i],this.smsForm.params[key]);
                }
            }
            this.smsForm.previewContent = content;

            that.$confirm('您确定发送该消息？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let paramsRequest = {
                    promotionId: that.couponInfo.promotionId,
                    phoneList: that.dataForm.phoneList,
                    smsThirdTemplateId: that.smsForm.tempId,
                    smsParams: that.smsForm.params
                }
                that.utils.request.backstageSendCoupon(paramsRequest,res=>{
                    if(res.code == '0000'){
                        that.sendSmsDialog = false;
                        that.backstageSendCouponDialog = false;
                        that.dialogVisible = true;
                        that.periodId = res.data;
                        //定时查询当前批次是否执行成功
                        that.$nextTick(()=>{
                            that.queryPeriodStatusInterval = setInterval(that.queryPeriodStatus,1000);
                        })
                    }

                })
            }).catch(() => { });
        },
        queryPeriodStatus(){
            this.utils.request.queryPeriodStatusById({id:this.periodId},res=>{
                if(res.code == '0000'){
                    if(res.data == 2){
                        this.dialogVisible = false;
                        clearInterval(this.queryPeriodStatusInterval);
                        this.$alert('发放成功', '', {
                            confirmButtonText: '确定',
                            callback: action => {
                                
                            }
                        });
                    }
                }else{
                    clearInterval(this.queryPeriodStatusInterval);
                }
            })
        },
        closeDialogVisible(){
            this.dialogVisible = false;
            clearInterval(this.queryPeriodStatusInterval);
        },
        /**
         * 刷新模版
         */
        refreshTemplate(){
            this.tTempalteListAll();
        },
        /**
         * 查询短信邮件模板
         */
        tTempalteListAll(){
            //查询短信
            this.utils.request.tTempalteListAll({status: 1, templateType: 1},res=>{
                if(res.code == '0000'){
                    this.templateList = res.data;
                }else{
                    this.templateList = []
                }
            })
        },


        //上传文件时处理方法  
        handleChange(file, fileList){
            this.fileTemp = file.raw;
            if(this.fileTemp){
                if((this.fileTemp.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') 
                    || (this.fileTemp.type == 'application/vnd.ms-excel')){
                    this.importfxx(this.fileTemp);
                } else {
                    this.$message({
                        type:'warning',
                        message:'附件格式错误，请删除后重新上传！'
                    })
                }
            } else {
                this.$message({
                    type:'warning',
                    message:'请上传附件！'
                })
            }
        },
        //超出最大上传文件数量时的处理方法
        handleExceed(){
            this.$message({
                type:'warning',
                message:'超出最大上传文件数量的限制！'
            })
            return;
        },
        //移除文件的操作方法
        handleRemove(file,fileList){
            this.fileTemp = null
        },

        /**
         * 读取
         */
        importfxx(obj) {
            let _this = this;
            let inputDOM = this.$refs.inputer;
            // 通过DOM取文件数据
 
            this.file = event.currentTarget.files[0];
 
            var rABS = false; //是否将文件读取为二进制字符串
            var f = this.file;
 
            var reader = new FileReader();
            FileReader.prototype.readAsBinaryString = function(f) {
                var binary = "";
                var rABS = false; //是否将文件读取为二进制字符串
                var pt = this;
                var wb; //读取完成的数据
                var outdata;
                var reader = new FileReader();
                reader.onload = function(e) {
                    var bytes = new Uint8Array(reader.result);
                    var length = bytes.byteLength;
                    for (var i = 0; i < length; i++) {
                        binary += String.fromCharCode(bytes[i]);
                    }
                    //此处引入，用于解析excel
                    var XLSX = require("xlsx");
                    if (rABS) {
                        wb = XLSX.read(btoa(fixdata(binary)), {
                        //手动转化
                        type: "base64"
                        });
                    } else {
                        wb = XLSX.read(binary, {
                        type: "binary"
                        });
                    }
                    outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); 
                    //outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
                    //此处可对数据进行处理
                    let arr = [];
                    outdata.map(v => {
                        // let obj = {};
                        // obj.phone = v["手机号"];
                        arr.push(v["手机号"]);
                    });
                    _this.importPhoneList = arr;
                    if(_this.importPhoneList != null && _this.importPhoneList.length > 0){
                        //回显至输入框
                        
                        //判断最后手机号是否输入,
                        let charPhone = _this.dataForm.phoneList.charAt(_this.dataForm.phoneList.length - 1);
                        if(charPhone != "" && charPhone != null && "," != charPhone){
                            _this.$set(_this.dataForm,"phoneList",_this.dataForm.phoneList+",");
                        }
                        _this.$set(_this.dataForm,"phoneList",_this.dataForm.phoneList+_this.importPhoneList.join(","))

                        _this.$refs.dataForm.clearValidate();
                    }


                    return arr;
                };
                reader.readAsArrayBuffer(f);
            };
            if (rABS) {
                reader.readAsArrayBuffer(f);
            } else {
                reader.readAsBinaryString(f);
            }
        },

    },
    created(){
        this.tTempalteListAll();
    },
    beforeDestroy() {
        //销毁定时器
        if(this.queryPeriodStatusInterval){
            clearInterval(this.queryPeriodStatusInterval);
        }
    }
}
</script>

<style lang="scss" scoped>
    /deep/ .el-form--inline {
        display: -webkit-box;
    }
    /deep/ .el-form-item__content{
        height: auto !important;
        line-height: 220%;
    }
    /deep/ .el-textarea__inner{
        min-height: auto !important;
        height: auto !important;
    }
    /deep/ .el-dialog__header{
        text-align: center;
    }
    .flex {
      line-height: 3;
      padding: 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
    }
    .phone {
        .el-form-item__content {
            display: flex;
            justify-content: flex-start;
        }
    }
    .labelMarginLeft5{
        /deep/ .el-form-item__label{
            margin-left: 10px;
        }
    }
    /deep/ .w495{
        width: 443px !important;
        .el-input__inner{
            width:443px !important;
        }
    }
    /deep/ .textareaParm{
        -webkit-appearance: none;
        background-color: #FFF;
        background-image: none;
        border-radius: 4px;
        border: 1px solid #DCDFE6;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        color: #606266;
        display: inline-block;
        font-size: inherit;
        outline: 0;
        padding: 0 15px;
        -webkit-transition: border-color .2s cubic-bezier(.645,.045,.355,1);
        transition: border-color .2s cubic-bezier(.645,.045,.355,1);
    }
    .log-title{
        display: flex;
        line-height: 50px ;
        justify-content: space-between;
    }

    .importPhone{
        display: flex;
        justify-content: flex-end;
        margin-bottom: 10px;
    }
    .importPhone-item{
        margin-left: 10px;
    }
    .download{
        color: #FFF;
        background-color: #409EFF;
        border-color: #409EFF;
        padding: 0 24px !important;
        border-radius: 4px;
        height: 32px !important;
        line-height: 32px !important;
        font-size: 16px !important;
        text-decoration: none;
    }
    .w632{
        width: 632px !important;
        /deep/ .el-input__inner{
            width: 632px !important;
        }
    }
    .ml26{
        margin-left: 26px;
    }
    .ml10{
        margin-left: 10px;
    }
</style>